package epoverty;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.ResultSetMetaData;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import net.miginfocom.swing.MigLayout;

public class Fundraisers extends JPanel
{
   private final int width = super.getWidth();
   private final int height = super.getHeight();
   private File photoFile;
   private BufferedImage defaultProfilePic = Util.resizeImage(ImageIO.read(new File("default.jpg")), 200, 200);
   private JPanel mainPanel;
   private Fundraisers.myTable fundraisersTable;
   private JTextField searchTF, raiseGoalTF, firstNameTF, middleNameTF, lastNameTF, phoneTF, emailTF,
      streetTF, cityTF, stateTF, zipTF, passwordTF;
   private static JComboBox fundraiserList, expeditionsList;
   private JLabel name, phone, email, street, cityState, tripName, status, goalRaised, picture;
   private JButton updateBTN, browseBTN;
   private static ArrayList<Object> possibleNames, formattedNames, tripsList, formattedTrips;
   private JCheckBox overrideCB;
   private JFileChooser photoFC;
   private JProgressBar goalProgress;
   private Connection conn;
   private int personID;
   private String personSelected;
   private boolean edit = false;
   private final JPanel editViewCardPanel;
   private final JButton viewBTN;
   private final JTextArea noteArea;
    private final JLabel pictureChange;

   Fundraisers(JTabbedPane tabs) throws IOException, ClassNotFoundException, SQLException, ParseException
   {
      //******************************************Set up UI
      UIManager.put("Table.background", Color.DARK_GRAY);
      UIManager.put("Table.foreground", Color.WHITE);
      UIManager.put("Table.font", new Font("SansSerif", Font.BOLD, 14));
      UIManager.put("Table.selectionBackground", Color.GREEN);
      UIManager.put("Table.selectionForeground", Color.BLACK);
      UIManager.put("Table.gridColor", Color.BLACK);
      UIManager.put("TableHeader.background", Color.GRAY);
      UIManager.put("TableHeader.foreground", Color.GREEN);
      UIManager.put("TableHeader.font", new Font("SansSerif", Font.BOLD, 16));
      UIManager.put("OptionPane.background", Color.DARK_GRAY);
      UIManager.put("OptionPane.messageForeground", Color.WHITE);
      UIManager.put("OptionPane.okButtonText", "Login");
      UIManager.put("Panel.background", Color.DARK_GRAY);
      UIManager.put("Label.foreground", Color.WHITE);
      UIManager.put("Label.foreground", Color.WHITE);
      UIManager.put("Label.font", new Font("Serif", Font.BOLD, 18));
      UIManager.put("TextField.font", new Font("Serif", Font.PLAIN, 18));
      UIManager.put("TextField.foreground", Color.BLACK);
      UIManager.put("Button.background", EPovertyMain.darkest);
      UIManager.put("Button.foreground", Color.WHITE);
      UIManager.put("TextField.background", new Color(100, 100, 100));
      UIManager.put("TextField.foreground", Color.WHITE);
      UIManager.put("TextField.caretForegroud", Color.WHITE);
      UIManager.put("PasswordField.background", new Color(100, 100, 100));
      UIManager.put("PasswordField.foreground", Color.WHITE);
      UIManager.put("CheckBox.background", Color.DARK_GRAY);
      UIManager.put("CheckBox.foreground", Color.WHITE);

      Border left = BorderFactory.createMatteBorder(4, 4, 4, 0, EPovertyMain.darkest);
      Border right = BorderFactory.createMatteBorder(4, 0, 4, 4, EPovertyMain.darkest);
      Border full = BorderFactory.createMatteBorder(2, 2, 2, 2, EPovertyMain.darkest);
      Border compoundProgress;
      Border raisedbevel = BorderFactory.createRaisedBevelBorder();
      Border loweredbevel = BorderFactory.createLoweredBevelBorder();
      Border border = BorderFactory.createLineBorder(Color.GREEN);
      compoundProgress = BorderFactory.createCompoundBorder(raisedbevel, loweredbevel);
      Border insideBorders = BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GREEN), compoundProgress);

      // *****************************************MAIN PANEL
      mainPanel = new JPanel();
      mainPanel.setLayout(new MigLayout("wrap 1, fill, insets 0"));
      mainPanel.setBorder(border);
      mainPanel.setBackground(Color.DARK_GRAY);

      // *****************************************CREATE FIRST PANEL (NAV BAR) IN TAB
      JPanel navPanel = new JPanel();
      //navPanel.setBorder(insideBorders);
      navPanel.setLayout(new MigLayout(
         "insets 3",
         "[grow][][center][][grow][]",
         ""));
      Dimension topNavDim = new Dimension(width, 40);
      // navPanel.setPreferredSize(topNavDim);
      GradientPaint paintNav = new GradientPaint(0, 150, Color.LIGHT_GRAY, 100, 50, Color.DARK_GRAY);
      // navPanel.setPaint(paintNav);

      // *****************************************CREATE SECOND PANEL (TABLE) IN TAB
      BackgroundPanel topFundraisersTab = new BackgroundPanel(null, BackgroundPanel.ACTUAL, 1.0f, 0.5f);
      topFundraisersTab.setBorder(insideBorders);
      topFundraisersTab.setLayout(new GridLayout(0, 1, 1, 1));
      GradientPaint paintTopFundraiser = new GradientPaint(0, 0, Color.BLACK, 100, 100, Color.DARK_GRAY);
      topFundraisersTab.setPaint(paintTopFundraiser);

      // *****************************************CREATE THIRD (PROGRESS BAR, ETC) PANEL IN TAB
      BackgroundPanel middleFundraisersTab = new BackgroundPanel(null, BackgroundPanel.ACTUAL, 1.0f, 0.5f);
      middleFundraisersTab.setBorder(insideBorders);
      middleFundraisersTab.setLayout(new MigLayout(
         "insets 0",
         "[]0[grow]10[]0[grow]10[]0[grow]",
         "[grow]0[]"));
      Dimension middleFundraiser = new Dimension(width, 60);
      middleFundraisersTab.setMinimumSize(middleFundraiser);
      GradientPaint paintmiddleFundraiser = new GradientPaint(0, 0, Color.DARK_GRAY, 100, 100, Color.DARK_GRAY);
      middleFundraisersTab.setPaint(paintmiddleFundraiser);

      // *****************************************CREATE FOURTH (VIEW AND EDIT) PANEL IN TAB
      editViewCardPanel = new JPanel(new CardLayout());


      // *****************************************CREATE AND ADD COMPONENTS TO NAV
      JLabel space0Label = new JLabel("");
      navPanel.add(space0Label, "");

      JButton previousButton = new JButton("Previous");
      navPanel.add(previousButton, "");

      possibleNames = DBconnection.getFundraisers();
      formattedNames = ArraySorter.sortArray(possibleNames);
      DBconnection.closeConnection();
      fundraiserList = new JComboBox(formattedNames.toArray());
      fundraiserList.setSelectedIndex(0);
      fundraiserList.setForeground(Color.BLACK);
      fundraiserList.setBackground(Color.WHITE);
      navPanel.add(fundraiserList, "width 250!, height 20!");

      JButton nextButton = new JButton("Next");
      navPanel.add(nextButton, "");

      JLabel space3Label = new JLabel("");
      navPanel.add(space3Label, "");

      searchTF = new JTextField("", 10);
      searchTF.setCaretColor(Color.WHITE);
      navPanel.add(searchTF, "height 20!");

      // *****************************************CREATE AND ADD TABLE TO THE TOP OF TAB
      fundraisersTable = new Fundraisers.myTable();
      JTable dataTable = new JTable(fundraisersTable);
      JScrollPane scrollPane = new JScrollPane(dataTable);
      dataTable.setFillsViewportHeight(true);
      topFundraisersTab.add(scrollPane);

      // *****************************************CREATE AND ADD COMPONENTS TO THE MIDDLE OF TAB    
      JLabel trip = new JLabel("TRIP:");
      trip.setBorder(left);
      middleFundraisersTab.add(trip, "growx, width 65:65:, height 30!");

      tripName = new JLabel(" ");
      tripName.setBorder(right);
      middleFundraisersTab.add(tripName, "growx, width 200:200:, height 30!");

      JLabel amountRaised = new JLabel("AMOUNT RAISED:");
      amountRaised.setBorder(left);
      middleFundraisersTab.add(amountRaised, "growx, width 170:170:, height 30!");

      goalRaised = new JLabel(" ");
      goalRaised.setBorder(right);
      middleFundraisersTab.add(goalRaised, "growx, width 200:200:, height 30!");

      JLabel statusLabel = new JLabel("STATUS:");
      statusLabel.setBorder(left);
      middleFundraisersTab.add(statusLabel, "growx, width 80:80:, height 30!");

      status = new JLabel(" ");
      status.setBorder(right);
      middleFundraisersTab.add(status, "growx, width 200:200:, height 30!, wrap");

      // SECOND ROW
      goalProgress = new JProgressBar();
      goalProgress.setBorder(full);
      middleFundraisersTab.add(goalProgress, "growx, span, height 20!");

      // ***************************************** CREATE AND ADD VIEW PANEL FOR BOTTOM
      String lineHeight = "25";
      
      
      BackgroundPanel viewPanel = new BackgroundPanel(null, BackgroundPanel.ACTUAL, 1.0f, 0.5f);
      viewPanel.setBorder(insideBorders);
      viewPanel.setLayout(new MigLayout("wrap 5"));
      GradientPaint paintBottomFundraiser = new GradientPaint(0, 150, Color.LIGHT_GRAY, 100, 50, Color.DARK_GRAY);
      viewPanel.setPaint(paintBottomFundraiser);
      

      tripsList = new ArrayList<Object>();
      formattedTrips = new ArrayList<Object>();
      // ROW 1
      JLabel nameLabel = new JLabel("Name: ");
      nameLabel.setForeground(EPovertyMain.font);
      viewPanel.add(nameLabel, "");

      name = new JLabel("");
      viewPanel.add(name, "width 400!, height "+lineHeight+"!, span 3");

      picture = new JLabel(new ImageIcon(defaultProfilePic));
      viewPanel.add(picture, "span 1  6, gapleft 25");
      Dimension photoSize = new Dimension(180, 180);
      picture.setMaximumSize(photoSize);
      picture.setMinimumSize(photoSize);

      // ROW 2
      JLabel phoneLabel = new JLabel("Phone Number: ");
      phoneLabel.setForeground(EPovertyMain.font);
      viewPanel.add(phoneLabel, "");

      phone = new JLabel("");
      viewPanel.add(phone, "width 250!, height "+lineHeight+"!");

      JLabel addressLabel = new JLabel("Address: ");
      addressLabel.setForeground(EPovertyMain.font);
      viewPanel.add(addressLabel, "");

      street = new JLabel(" ");
      viewPanel.add(street, "width 250!, height "+lineHeight+"!");

      // ROW 3
      JLabel emailLabel = new JLabel("E-Mail: ");
      emailLabel.setForeground(EPovertyMain.font);
      viewPanel.add(emailLabel, "");
      
      email = new JLabel("");
      viewPanel.add(email, "width 250!, height "+lineHeight+"!");

      JLabel blankAddressLabel = new JLabel("");
      viewPanel.add(blankAddressLabel, "");

      cityState = new JLabel(" ");
      viewPanel.add(cityState, "width 250!, height "+lineHeight+"!");

      // ROW 4
      JLabel notesLabel = new JLabel("Notes");
      notesLabel.setForeground(EPovertyMain.font);
      viewPanel.add(notesLabel, "height "+lineHeight+"!");

      noteArea = new JTextArea(5, 20);
      JScrollPane notesscrollPane = new JScrollPane(noteArea); 
      notesscrollPane.getVerticalScrollBar().setPreferredSize (new Dimension(0,0));
      noteArea.setEditable(true);

      viewPanel.add(notesscrollPane, "width 560!, span 3 2");

      // ROW 5
      JLabel emptyTripLabel = new JLabel("");
      viewPanel.add(emptyTripLabel, "width 150!, height "+lineHeight+"!");

      // ROW 6
      updateBTN = new JButton("Edit");
      viewPanel.add(updateBTN, "");
      updateBTN.setOpaque(true);

      
      // ***************************************** CREATE AND ADD EDIT PANEL FOR BOTTOM
      BackgroundPanel editPanel = new BackgroundPanel(null, BackgroundPanel.ACTUAL, 1.0f, 0.5f);
      editPanel.setBorder(insideBorders);
      editPanel.setLayout(new MigLayout("wrap 5"));
      editPanel.setPaint(paintBottomFundraiser);
      
      // ROW 1
      nameLabel = new JLabel("Name: ");
      nameLabel.setForeground(EPovertyMain.font);
      editPanel.add(nameLabel, "");

      firstNameTF = new JTextField();
      middleNameTF = new JTextField();
      lastNameTF = new JTextField();
      JPanel nameEditPanel = new JPanel(new MigLayout("insets 0"));
      nameEditPanel.add(lastNameTF, "width 150!, height "+lineHeight+"!");
      nameEditPanel.add(new JLabel(","), "bottom");
      nameEditPanel.add(firstNameTF, "width 100!, height "+lineHeight+"!");
      nameEditPanel.add(middleNameTF, "width 100!, height "+lineHeight+"!");
      editPanel.add(nameEditPanel, "width 400!, height "+lineHeight+"!, span 3");

      pictureChange = new JLabel(new ImageIcon(defaultProfilePic));
      editPanel.add(pictureChange, "span 1  6, gapleft 25");
      pictureChange.setMaximumSize(photoSize);
      pictureChange.setMinimumSize(photoSize);

      // ROW 2
      phoneLabel = new JLabel("Phone Number: ");
      phoneLabel.setForeground(EPovertyMain.font);
      editPanel.add(phoneLabel, "");

      phoneTF = new JTextField();
      editPanel.add(phoneTF, "width 250!, height "+lineHeight+"!");

      addressLabel = new JLabel("Address: ");
      addressLabel.setForeground(EPovertyMain.font);
      editPanel.add(addressLabel, "");

      streetTF = new JTextField();
      editPanel.add(streetTF, "width 250!, height "+lineHeight+"!");

      // ROW 3
      emailLabel = new JLabel("E-Mail: ");
      emailLabel.setForeground(EPovertyMain.font);
      editPanel.add(emailLabel, "");
      
      emailTF = new JTextField();
      editPanel.add(emailTF, "width 250!, height "+lineHeight+"!");

      blankAddressLabel = new JLabel("");
      viewPanel.add(blankAddressLabel, "");
      editPanel.add(blankAddressLabel, "");

      cityTF = new JTextField();
      stateTF = new JTextField();
      zipTF = new JTextField();
      JPanel cityStateEditPanel = new JPanel(new MigLayout("insets 0"));
      cityStateEditPanel.add(cityTF, "width 125!, height "+lineHeight+"!");
      cityStateEditPanel.add(new JLabel(","), "bottom");
      cityStateEditPanel.add(stateTF, "width 25!, height "+lineHeight+"!");
      cityStateEditPanel.add(zipTF, "width 70!, height "+lineHeight+"!");
      editPanel.add(cityStateEditPanel, "width 250!, height "+lineHeight+"!");

      // ROW 4
      JLabel passwordLabel = new JLabel("Password: ");
      passwordLabel.setForeground(EPovertyMain.font);
      editPanel.add(passwordLabel, "");

      passwordTF = new JPasswordField();
      editPanel.add(passwordTF, "width 250!, height "+lineHeight+"!");

      JLabel progressLabel = new JLabel("Goal: ");
      progressLabel.setForeground(EPovertyMain.font);
      editPanel.add(progressLabel, "");

      raiseGoalTF = new JTextField();
      editPanel.add(raiseGoalTF, "width 150!, height "+lineHeight+"!");

      // ROW 5
      JLabel tripLabel = new JLabel("Trip: ");
      progressLabel.setForeground(EPovertyMain.font);
      editPanel.add(tripLabel, "width 150!, height "+lineHeight+"!");

      expeditionsList = new JComboBox();
      editPanel.add(expeditionsList, "width 150!, height "+lineHeight+"!");

      overrideCB = new JCheckBox("Override Eligibility?");
      editPanel.add(overrideCB, "width 150!, height "+lineHeight+"!, span 2, wrap");

      // ROW 6
      viewBTN = new JButton("Done");
      editPanel.add(viewBTN, "");
      viewBTN.setOpaque(true);
      
      JLabel pictureChangeLabel = new JLabel("Click on picture to change.");
      editPanel.add(pictureChangeLabel, "span 3, right");
      
      // Extra photo stuff
      photoFC = new JFileChooser();
      FileFilter photoFilter = new FileNameExtensionFilter("Image Files", "jpg", "jpeg", "png");
      photoFC.setFileFilter(photoFilter);
      
      editViewCardPanel.add(viewPanel, "view");
      editViewCardPanel.add(editPanel, "edit");
      
      
      // CALL UPDATES TO INITIALIZE THE TABLE AND CONTACT INFO 
      personSelected = fundraiserList.getSelectedItem().toString();
      personID = ArraySorter.idFinder(possibleNames, personSelected);
      updateContactInfo(personID);
      updateTable(personID);

      // ADD TOP AND BOTTOM TO THE MAIN AND PUT THEM INTO A TAB
      mainPanel.add(navPanel, "growx");
      mainPanel.add(topFundraisersTab, "grow");
      mainPanel.add(middleFundraisersTab, "growx");
      mainPanel.add(editViewCardPanel, "grow");

      mainPanel.revalidate();
      tabs.add("", mainPanel);

      /**
       * Action listener for the previous button
       */
      previousButton.addActionListener(
         new ActionListener()
         {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                if (edit){
                    viewBTN.doClick();
                }
                
               int selectedIndex = fundraiserList.getSelectedIndex();

               if (selectedIndex > 0)
               {
                  selectedIndex--;
               }
               fundraiserList.setSelectedIndex(selectedIndex);
            }
         });

      /**
       * Action listener for the next button
       */
      nextButton.addActionListener(
         new ActionListener()
         {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                if (edit){
                    viewBTN.doClick();
                }
                
               int selectedIndex = fundraiserList.getSelectedIndex();
               int selectedMax = fundraiserList.getItemCount();

               if (selectedIndex < (selectedMax - 1))
               {
                  selectedIndex++;
               }
               fundraiserList.setSelectedIndex(selectedIndex);
            }
         });
      
      pictureChange.addMouseListener(new MouseListener(){
            @Override
            public void mouseClicked(MouseEvent me) {
                System.out.println("Mouse Click");
                // GETS THE APPROVED PICTURE AND STORES IT AS THE photoFILE TO BE UPLOADED
                if (photoFC.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                    photoFile = photoFC.getSelectedFile();
                    
                    try {
                        BufferedImage photoImage;
                        photoImage = ImageIO.read(photoFile);
                        photoImage = Util.resizeImage(photoImage, 200, 200);
                        pictureChange.setIcon(new ImageIcon(photoImage));
                    } catch (IOException ex) {
                        Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    
                    
                }

            }

            @Override
            public void mousePressed(MouseEvent me) {
                // Not Supported
            }

            @Override
            public void mouseReleased(MouseEvent me) {
                // Not Supported
            }

            @Override
            public void mouseEntered(MouseEvent me) {
                // Not Supported
            }

            @Override
            public void mouseExited(MouseEvent me) {
                // Not Supported
            }
          
      });

      /**
       * Action listener for notes section
       */
      noteArea.addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent fe) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void focusLost(FocusEvent fe) {
                personSelected = fundraiserList.getSelectedItem().toString();
                personID = ArraySorter.idFinder(possibleNames, personSelected);
                try {
                    updateNotes(personID);
                } catch (SQLException ex) {
                    Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NoSuchAlgorithmException ex) {
                    Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                } catch (UnsupportedEncodingException ex) {
                    Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ParseException ex) {
                    Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
      //*********************************************ACTION LISTENER FOR UPDATE BUTTON
      updateBTN.addActionListener(editViewButtonsActionListener);
      viewBTN.addActionListener(editViewButtonsActionListener);

      searchTF.addKeyListener(
         new KeyListener()
         {
            @Override
            public void keyTyped(KeyEvent e)
            {
            }

            @Override
            public void keyPressed(KeyEvent e)
            {
            }

            @Override
            public void keyReleased(KeyEvent e)
            {
               JTextField textField = (JTextField) e.getSource();
               String text = textField.getText();
               textField.setText(text);
               try
               {
                  updateComboBox();
               }
               catch (SQLException ex)
               {
                  Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
               }
               catch (ClassNotFoundException ex)
               {
                  Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
               }
            }
         });

      // ITEM LISTENER FOR COMBO BOX
      fundraiserList.addItemListener(
         new ItemListener()
         {
            @Override
            public void itemStateChanged(ItemEvent e)
            {
               // WHEN SOMEONE IS SELECTED FROM THE COMBOBOX GET THEIR INFORMATION
               if (e.getStateChange() == ItemEvent.DESELECTED)
               {
                   
               }
               if (e.getStateChange() == ItemEvent.SELECTED)
               {            
                   String name;
                   if (edit)
                   {
                       name = "view";
                       edit = false;
                       CardLayout cl = (CardLayout) (editViewCardPanel.getLayout());
                       cl.show(editViewCardPanel, name);
                   }                   
                   
                  personSelected = fundraiserList.getSelectedItem().toString();
                  personID = ArraySorter.idFinder(possibleNames, personSelected);
                  // UPDATE CONTACT INFO AND TABLE
                  try
                  {
                     updateContactInfo(personID);
                    
                     try
                     {
                        updateTable(personID);
                     }
                     catch (ParseException ex)
                     {
                        Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                     }

                  }
                  catch (IOException ex)
                  {
                     Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  catch (ClassNotFoundException ex)
                  {
                     Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  catch (SQLException ex)
                  {
                     Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                  }
               }
            }
         });
      // END OF ITEM LISTENER FOR COMBO BOX      
   }

   /**
    * Action Listener used by the update and done buttons
    */
   private ActionListener editViewButtonsActionListener = new ActionListener()
         {
            @Override
            public void actionPerformed(ActionEvent e)
            {
               personSelected = fundraiserList.getSelectedItem().toString();
               personID = ArraySorter.idFinder(possibleNames, personSelected);


               String name;
               if (!edit)
               {
                  name = "edit";
                  edit = true;
               }
               else
               {
                  name = "view";
                  edit = false;

                  // Update
                  try
                  {
                     // CALL TO UPDATE THE DATABASE
                     updateDatabase(personID);
                  }
                  catch (IOException ex)
                  {
                     Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  catch (NoSuchAlgorithmException ex)
                  {
                     Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  catch (SQLException ex)
                  {
                     Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  catch (ClassNotFoundException ex)
                  {
                     Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  catch (ParseException ex)
                  {
                     Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
                  }
               }

               CardLayout cl = (CardLayout) (editViewCardPanel.getLayout());
               cl.show(editViewCardPanel, name);

               // Populate Trip List
               try
               {
                  tripsList = DBconnection.getTrips();
                  formattedTrips = ArraySorter.sortArray(tripsList);
               }
               catch (SQLException ex)
               {
                  Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
               }
               catch (ClassNotFoundException ex)
               {
                  Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
               }
               expeditionsList.setModel(new DefaultComboBoxModel(formattedTrips.toArray()));

               try
               {
                  // UPDATE THE INFORMATION DISPLAYED TO THE PERSON SELECTED
                  getInfoForUpdate(personID);
               }
               catch (SQLException ex)
               {
                  Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
               }
               catch (ClassNotFoundException ex)
               {
                  Logger.getLogger(Fundraisers.class.getName()).log(Level.SEVERE, null, ex);
               }
            }
         };
   
   // ********************************************METHOD TO UPDATE CONTACT INFO BASED ON PERSON SELECTED
   private void updateContactInfo(int personID) throws SQLException, ClassNotFoundException, IOException
   {
       String getInfoQuery = "SELECT p.firstName, p.middleName, p.lastName, p.phoneNumber, "
               + "p.emailAddress, p.notes, p.addressStreet, p.addressCity, "
               + "addressState, addressZip, f.eligibilityOverridden "
               + "FROM persons AS p, fundraisers AS f "
               + "WHERE p.personID = " +personID +" AND f.personId = p.personId";
       
      String allInfo = "";

      conn = DBconnection.getConnection();
      PreparedStatement stmt = (PreparedStatement) conn.prepareStatement(getInfoQuery);
      ResultSet rs = (ResultSet) stmt.executeQuery();
      ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();
      int columns = md.getColumnCount();

      // GET ALL THE DATA FOR THE PERSON
      if (rs.next())
      {
         for (int i = 1; i <= columns; i++)
         {
            if (rs.getObject(i) != null)
            {
               allInfo = allInfo + rs.getObject(i);
            }
            else
            {
               allInfo = allInfo + " ";
            }
            allInfo = allInfo + ",";
         }
      }

      rs.close();
      stmt.close();
      // PUT THE DATA INTO AN ARRAY AND USE THAT TO RECREATE INFO ON SCREEN
      String[] results = allInfo.split(",");
      BufferedImage profilePicture = DBconnection.getPhoto(personID);
      if (profilePicture != null)
      {
         profilePicture = Util.resizeImage(profilePicture, 400, 400);
         picture.setIcon(new ImageIcon(profilePicture));
         pictureChange.setIcon(new ImageIcon(profilePicture));
      }
      else
      {
         picture.setIcon(new ImageIcon(defaultProfilePic));
         pictureChange.setIcon(new ImageIcon(defaultProfilePic));
      }
      name.setText(results[2] + ", " + results[0] + " " + results[1]);
      if (results.length > 3)
      {
          if (!results[3].isEmpty())
          {
              phone.setText(String.format("(%s) %s-%s", results[3].substring(0, 3), results[3].substring(3, 6),
                      results[3].substring(6, 10)));
          }
          else
          {
              phone.setText("(  )  -    ");
          }
      }
      else
      {
         phone.setText("(  )  -    ");
      }
      if (results.length > 4)
      {
         email.setText(results[4]);
      }
      else
      {
         email.setText("");
      }
      if (results.length > 5)
      {
         noteArea.setText(results[5]);
      }
      else
      {
         email.setText("");
      }
      if (results.length > 6)
      {
         street.setText(results[6]);
      }
      else
      {
         street.setText("");
      }
      if (results.length > 9 && !results[7].replaceAll("\\s","").equals(""))
      {
         cityState.setText(results[7] + ", " + results[8] + " " + results[9]);
      }
      else if (results.length > 8 && !results[7].replaceAll("\\s","").equals(""))
      {
         cityState.setText(results[7] + ", " + results[8]);
      }
      else if (results.length > 7)
      {
         cityState.setText(results[7]);
      }
      else
      {
         cityState.setText("");
      }
      if (results.length > 10)
      {
          if (results[10].equalsIgnoreCase("1")) 
          {
              overrideCB.setSelected(true);
          } else 
          {
              overrideCB.setSelected(false);
          }
      }

      DBconnection.closeConnection();
   }

   // ********************************************METHOD TO UPDATE CONTACT INFO BASED ON PERSON SELECTED
   private void getInfoForUpdate(int personID) throws SQLException, ClassNotFoundException
   {
      String getInfoQuery = "SELECT "
         + "firstName, middleName, lastName, phoneNumber, emailAddress, "
         + "addressStreet, addressCity, addressState, addressZip, password, raiseGoal, expeditionId "
         + "FROM persons, fundraisers WHERE persons.personId =" + personID
         + " AND fundraisers.personId = " + personID;
      String allInfo = "";

      conn = DBconnection.getConnection();
      PreparedStatement stmt = (PreparedStatement) conn.prepareStatement(getInfoQuery);
      ResultSet rs = (ResultSet) stmt.executeQuery();
      ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();
      int columns = md.getColumnCount();

      // GET ALL THE DATA FROM THE PERSONS AND FUNDRAISERS TABLES
      if (rs.next())
      {
         for (int i = 1; i <= columns; i++)
         {
            if (rs.getObject(i) != null)
            {
               allInfo = allInfo + rs.getObject(i);
            }
            else
            {
               allInfo = allInfo + " ";
            }
            allInfo = allInfo + ",";
         }
      }
      String[] results = allInfo.split(",");


      // EXPEDITION LIST
      String getExpeditionQuery = "SELECT "
         + "expeditionId, @rownum:=@rownum+1 'number' "
         + "FROM expeditions, (SELECT @rownum:=0) r "
         + "WHERE expeditions.expeditionId =" + results[11];

      stmt = (PreparedStatement) conn.prepareStatement(getExpeditionQuery);
      rs = (ResultSet) stmt.executeQuery();
      md = (ResultSetMetaData) rs.getMetaData();
      columns = md.getColumnCount();

      // GET ALL THE DATA FROM THE PERSONS AND FUNDRAISERS TABLES
      allInfo = "";
      if (rs.next())
      {
         for (int i = 1; i <= columns; i++)
         {
            if (rs.getObject(i) != null)
            {
                System.out.println("object " +i +" " + rs.getObject(i).toString());
               allInfo += rs.getObject(i);
            }
            else
            {
               allInfo = allInfo + " ";
            }
            allInfo = allInfo + ",";
         }
      }
      String[] expResults = allInfo.split(",");

      // PUT THE DATA INTO AN ARRAY AND USE THAT TO RECREATE INFO ON SCREEN
      firstNameTF.setText(results[0]);
      middleNameTF.setText(results[1]);
      lastNameTF.setText(results[2]);
      phoneTF.setText(results[3]);
      emailTF.setText(results[4]);
      streetTF.setText(results[5]);
      cityTF.setText(results[6]);
      stateTF.setText(results[7]);
      zipTF.setText(results[8]);
      passwordTF.setText(results[9]);
      raiseGoalTF.setText(results[10]);
      expeditionsList.setSelectedIndex(Integer.parseInt(expResults[0]));

      // CHECK IF THE PERSON HAS AN ELIGIBILITY OVERRIDE FOR CUTOFF DATE

      // GET ALL THE EXPEDITION NAMES
      rs.close();
      stmt.close();
      DBconnection.closeConnection();
   }

   // ********************************************METHOD TO UPDATE THE TABLE
   private void updateTable(int personId) throws SQLException, ClassNotFoundException, ParseException
   {
      // CLEAR THE TABLE
      fundraisersTable.getDataVector().removeAllElements();

      String donationsMadeQuery = "SELECT CONCAT(p.firstName, ' ', p.lastName), d.donationAmount, "
         + "DATE_FORMAT(d.donationDate, '%b %D, %Y') as Date "
         + "FROM persons AS p, donations AS d, fundraisers AS f, donors AS dnr "
         + "WHERE p.personId = dnr.personId "
         + "AND dnr.donorId = d.donorId "
         + "AND d.fundraiserId = f.fundraiserId "
         + "AND f.personId = " + personId;

      String tripStatusQuery = "SELECT e.name, e.cutoffDate, f.raiseGoal, f.raised, f.eligibilityOverridden "
         + "FROM expeditions AS e, fundraisers AS f "
         + "WHERE f.personId = " + personId + " "
         + "AND f.expeditionId = e.expeditionId";

      // GET CONNECTION AND RUN QUERY FOR TABLE
      Connection ePoverty = DBconnection.getConnection();
      PreparedStatement tableStmt = (PreparedStatement) ePoverty.prepareStatement(donationsMadeQuery);
      ResultSet tableRS = (ResultSet) tableStmt.executeQuery();
      ResultSetMetaData tableMD = (ResultSetMetaData) tableRS.getMetaData();


      // PUT THE META DATA INTO THE TABLE
      int fundraiserColCount = tableMD.getColumnCount();
      String[] columnNames =
      {
         "DONOR", "AMOUNT", "DATE"
      };
      fundraisersTable.setColumnIdentifiers(columnNames);

      while (tableRS.next())
      {
         Object[] data = new String[fundraiserColCount];
         for (int i = 1; i <= fundraiserColCount; i++)
         {
            data[i - 1] = tableRS.getString(i);
         }
         fundraisersTable.addRow(data);
      }
      fundraisersTable.fireTableDataChanged();

      // CLOSE STATEMENT and RESULT SET
      tableRS.close();
      tableStmt.close();

      // RUN QUERY FOR TRIP STATUS BAR
      PreparedStatement statusStmt = (PreparedStatement) ePoverty.prepareStatement(tripStatusQuery);
      ResultSet statusRS = (ResultSet) statusStmt.executeQuery();
      ResultSetMetaData statusMD = (ResultSetMetaData) statusRS.getMetaData();
      String allInfo = "";
      int columns = statusMD.getColumnCount();
      if (statusRS.next())
      {
         for (int i = 1; i <= columns; i++)
         {
            if (statusRS.getObject(i) != null)
            {
               allInfo = allInfo + statusRS.getObject(i);
            }
            else
            {
               allInfo = allInfo + " ";
            }
            allInfo = allInfo + ",";
         }
      }

       // PUT DATA INTO AN ARRAY AND USE FOR STATUS UPDATE
       String[] results = allInfo.split(",");
       double raisedAmount = Double.parseDouble(results[3]);
       double tripCost = Double.parseDouble(results[2]);
       int raisedNumber = (int) raisedAmount;
       int costOfTrip = (int) tripCost;
       String override = results[4];
       // GET STRINGS OF DATES INTO DATE FORMAT
       String fundraiserDateMetGoal = DBconnection.getFundraisersGoalReachedDay(personId);
       DateFormat formatter;
       java.util.Date cutoffDate;
       java.util.Date metGoalDate;
       formatter = new SimpleDateFormat("yyyy-MM-dd");
       cutoffDate = (java.util.Date) formatter.parse(results[1]);
       if (fundraiserDateMetGoal == null || fundraiserDateMetGoal.equalsIgnoreCase("0000-00-00 00:00:00")) 
       {
           metGoalDate = null;
       } 
       else 
       {
           metGoalDate = (java.util.Date) formatter.parse(fundraiserDateMetGoal);
       }

      // IF NULL
       if (fundraiserDateMetGoal == null || fundraiserDateMetGoal.equalsIgnoreCase("0000-00-00 00:00:00")) 
       {
           // IF IN HERE NO dateMetRaiseGoal has been entered (null)
           if (raisedNumber >= costOfTrip && override.equalsIgnoreCase("true")) 
           {
               status.setText("ELIGIBLE");
               status.setForeground(Color.GREEN);
               goalRaised.setText("$" + raisedNumber + "/$" + costOfTrip);
               goalRaised.setForeground(Color.GREEN);
               tripName.setText(results[0]);
               tripName.setForeground(Color.GREEN);
               goalProgress.setMaximum(costOfTrip);
               goalProgress.setValue(raisedNumber);
               goalProgress.setForeground(Color.GREEN);
           }
           else 
           {
               status.setText("INELIGIBLE");
               status.setForeground(new Color(244, 38, 44));
               goalRaised.setText("$" + raisedNumber + "/$" + costOfTrip);
               goalRaised.setForeground(new Color(244, 38, 44));
               tripName.setText(results[0]);
               tripName.setForeground(new Color(244, 38, 44));
               goalProgress.setMaximum(costOfTrip);
               goalProgress.setValue(raisedNumber);
               goalProgress.setForeground(new Color(244, 38, 44));
           }
       } 
       else if (raisedNumber >= costOfTrip && cutoffDate.after(metGoalDate)) 
       {
           status.setText("ELIGIBLE");
           status.setForeground(Color.GREEN);
           goalRaised.setText("$" + raisedNumber + "/$" + costOfTrip);
           goalRaised.setForeground(Color.GREEN);
           tripName.setText(results[0]);
           tripName.setForeground(Color.GREEN);
           goalProgress.setMaximum(costOfTrip);
           goalProgress.setValue(raisedNumber);
           goalProgress.setForeground(Color.GREEN);
       }
       else if (raisedNumber >= costOfTrip && cutoffDate.equals(metGoalDate)) 
       {
           status.setText("ELIGIBLE");
           status.setForeground(Color.GREEN);
           goalRaised.setText("$" + raisedNumber + "/$" + costOfTrip);
           goalRaised.setForeground(Color.GREEN);
           tripName.setText(results[0]);
           tripName.setForeground(Color.GREEN);
           goalProgress.setMaximum(costOfTrip);
           goalProgress.setValue(raisedNumber);
           goalProgress.setForeground(Color.GREEN);
       }
       else if (raisedNumber >= costOfTrip && override.equalsIgnoreCase("true")) 
       {    
           status.setText("ELIGIBLE");
           status.setForeground(Color.GREEN);
           goalRaised.setText("$" + raisedNumber + "/$" + costOfTrip);
           goalRaised.setForeground(Color.GREEN);
           tripName.setText(results[0]);
           tripName.setForeground(Color.GREEN);
           goalProgress.setMaximum(costOfTrip);
           goalProgress.setValue(raisedNumber);
           goalProgress.setForeground(Color.GREEN);
       }
       else
       {
           status.setText("INELIGIBLE");
           status.setForeground(new Color(244, 38, 44));
           goalRaised.setText("$" + raisedNumber + "/$" + costOfTrip);
           goalRaised.setForeground(new Color(244, 38, 44));
           tripName.setText(results[0]);
           tripName.setForeground(new Color(244, 38, 44));
           goalProgress.setMaximum(costOfTrip);
           goalProgress.setValue(raisedNumber);
           goalProgress.setForeground(new Color(244, 38, 44));
       }


      //CLOSE CONNECTIONS
      statusRS.close();
      statusStmt.close();
      DBconnection.closeConnection();
   }

   // ********************************************METHOD TO UPDATE DATABASE
   private void updateDatabase(int personId) throws SQLException, ClassNotFoundException, NoSuchAlgorithmException, UnsupportedEncodingException, IOException, ParseException
   {
      int override;
      // See if override is selected
      if (overrideCB.isSelected())
      {
          override = 1;
      }
      else
      {
          override = 0;
      }
      String expeditionName = expeditionsList.getSelectedItem().toString();
      int expeditionID = ArraySorter.idFinder(tripsList, expeditionName);
      String updatePersonsQuery;
      String passwordCheckQuery = "SELECT password FROM persons WHERE personId = " + personId;
      String updateFundraisersQuery = "UPDATE fundraisers SET raiseGoal = \"" + raiseGoalTF.getText() + "\" "
         + ", expeditionId = " + expeditionID
         + ", eligibilityOverridden = " +override     
         + " WHERE fundraisers.personId = " + personId;
      conn = DBconnection.getConnection();
      PreparedStatement checkPW = (PreparedStatement) conn.prepareStatement(passwordCheckQuery);
      ResultSet passRS = (ResultSet) checkPW.executeQuery();
      passRS.next();
            
      // CHECK IF PASSWORD ENTERED IS THE SAME AS THAT STORED IN THE DB (if it is don't rehash it and store again)!!
      if (passwordTF.getText().equals(passRS.getObject(1)))
      {
         updatePersonsQuery = "UPDATE persons SET firstName = \"" + firstNameTF.getText() + "\""
                  + ", middleName = \"" + middleNameTF.getText() + "\""
                  + ", lastName = \"" + lastNameTF.getText() + "\""
                  + ", phoneNumber = \"" + phoneTF.getText() + "\""
                  + ", emailAddress = \"" + emailTF.getText() + "\""
                  + ", addressStreet = \"" + streetTF.getText() + "\""
                  + ", addressCity = \"" + cityTF.getText() + "\""
                  + ", addressState = \"" + stateTF.getText() + "\""
                  + ", addressZip = \"" + zipTF.getText() + "\""
                  + " WHERE persons.personId = " + personId;
      }
      else
      {
         updatePersonsQuery = "UPDATE persons SET firstName = \"" + firstNameTF.getText() + "\""
                  + ", middleName = \"" + middleNameTF.getText() + "\""
                  + ", lastName = \"" + lastNameTF.getText() + "\""
                  + ", phoneNumber = \"" + phoneTF.getText() + "\""
                  + ", emailAddress = \"" + emailTF.getText() + "\""
                  + ", addressStreet = \"" + streetTF.getText() + "\""
                  + ", addressCity = \"" + cityTF.getText() + "\""
                  + ", addressState = \"" + stateTF.getText() + "\""
                  + ", addressZip = \"" + zipTF.getText() + "\""
                  + ", password = \"" + SimpleSHA1.SHA1(passwordTF.getText()) + "\""
                  + " WHERE persons.personId = " + personId;
      }
      //RUN THE UPDATE QUERIES         
      PreparedStatement tableStmt = (PreparedStatement) conn.prepareStatement(updatePersonsQuery);
      tableStmt.executeUpdate();
      tableStmt = (PreparedStatement) conn.prepareStatement(updateFundraisersQuery);
      tableStmt.executeUpdate();

      //UPDATE PICTURE
      if (photoFile != null)
      {
         BufferedImage photoImage = ImageIO.read(photoFile);
         photoImage = Util.resizeImage(photoImage, 200, 200);
         DBconnection.updatePhoto(personId, photoImage);
         //SET photoFile to null SO IT DOESN'T UPDATE FOR FUTURE UPDATES
         photoFile = null;
      }

      tableStmt.close();
      DBconnection.closeConnection();

      // UPDATE CONTACT INFO TO DISPLAY CHANGES
      int selected = fundraiserList.getSelectedIndex();
      updateFundraiserList();
      Donors.updateDonorList();
      updateContactInfo(personId);
      updateTable(personId);
      fundraiserList.setSelectedIndex(selected);  
   }
   
   private void updateNotes(int personId) throws SQLException, ClassNotFoundException, NoSuchAlgorithmException, UnsupportedEncodingException, IOException, ParseException
   {
      String updatePersonsQuery;
      conn = DBconnection.getConnection();
      // CHECK IF PASSWORD ENTERED IS THE SAME AS THAT STORED IN THE DB (if it is don't rehash it and store again)!!
        updatePersonsQuery = "UPDATE persons SET notes = \"" + noteArea.getText() + "\""
        + " WHERE persons.personId = " + personId;
      //RUN THE UPDATE QUERIES         
      PreparedStatement tableStmt = (PreparedStatement) conn.prepareStatement(updatePersonsQuery);
      tableStmt.executeUpdate();

      tableStmt.close();
      DBconnection.closeConnection();

      // UPDATE CONTACT INFO TO DISPLAY CHANGES
      updateContactInfo(personId);
      updateTable(personId);
   }

   // **************************************UPDATES THE COMBO BOX TO REFLECT ALL FUNDRAISERS MATCHING SEARCH CRITERIA
   private void updateComboBox() throws SQLException, ClassNotFoundException
   {
      Object[] fundraiserNames = formattedNames.toArray();

      Pattern p = Pattern.compile(searchTF.getText(), Pattern.CASE_INSENSITIVE);
      fundraiserList.removeAllItems();
      for (int i = 0; i < fundraiserNames.length; i++)
      {
         String elem = fundraiserNames[i].toString();
         Matcher m = p.matcher(elem);
         if (m.find())
         {
            fundraiserList.addItem(fundraiserNames[i]);
         }
      }
   }

   // ********************************************METHOD THAT ALLOWS OTHER CLASSES TO UPDATE THE FUNDRAISER LIST
   public static void updateFundraiserList() throws SQLException, ClassNotFoundException
   {
      possibleNames = DBconnection.getFundraisers();
      formattedNames = ArraySorter.sortArray(possibleNames);
      Object[] arrayOfNames = formattedNames.toArray();
      fundraiserList.removeAllItems();
      for (int x = 0; x < formattedNames.size(); x++)
      {
         fundraiserList.addItem(arrayOfNames[x]);
      }
   }

   //Prevents cells from being edited in table by overriding isCellEditable.
   public class myTable extends DefaultTableModel
   {
      @Override
      public boolean isCellEditable(int row, int col)
      {
         return false;
      }
   }
}
